package com.shxy.cloudclassroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.entity.vo.ForumPostDetailVO;
import com.shxy.cloudclassroom.mapper.ForumPostMapper;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.shxy.cloudclassroom.utils.SystemConstant.LOGIN_USER;

@Service
public class ForumPostServiceImpl extends ServiceImpl<ForumPostMapper, ForumPost> implements ForumPostService {
    
    @Resource
    private ForumCategoryService forumCategoryService;
    
    @Resource
    private ForumReplyService forumReplyService;
    
    @Resource
    private UserService userService;

    @Override
    // 获取论坛帖子列表
    public List<ForumPost> getForumPostList(Page<ForumPost> forumPostPage, LambdaQueryWrapper<ForumPost> wrapper) {
        return this.list(forumPostPage, wrapper);
    }

    @Override
    // 发布帖子
    public Map<String, Object> publishPost(ForumPost post, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("redirect", "redirect:/login");
                return result;
            }
            post.setAuthorId(user.getId());
            post.setIsTop(0);
            post.setIsElite(0);
            post.setStatus(1);
            post.setCreatedTime(LocalDateTime.now());
            post.setUpdatedTime(LocalDateTime.now());
            this.save(post);
            result.put("success", true);
            result.put("redirect", "redirect:/forum/list");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发布帖子失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 获取帖子详情
    public ForumPostDetailVO getPostDetail(Integer id, Integer page, Integer size, HttpSession session) {
        try {
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                return null;
            }
            // 1.查询帖子
            ForumPost post = this.getById(id);
            if (post == null) {
                return null;
            }
            // 增加浏览次数
            post.setViewCount(post.getViewCount() + 1);
            this.updateById(post);
            // 2.查询帖子关联的回复记录并按更新时间排序
            Page<ForumReply> replyPage = new Page<>(page, size);
            LambdaQueryWrapper<ForumReply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ForumReply::getPostId, id).orderByDesc(ForumReply::getUpdatedTime);
            Page<ForumReply> resultPage = forumReplyService.page(replyPage, wrapper);
            // 3.获取板块分类
            ForumCategory category = forumCategoryService.getById(post.getCategoryId());
            // 4.获取回复作者信息并转换为 Map渲染前端
            //4.1获取所有回复表对应的用户id,并且做去重处理，因为一个用户可能多条评论
            List<Long> authorIds = resultPage.getRecords().stream()
                    .map(ForumReply::getAuthorId)
                    .distinct()
                    .collect(Collectors.toList());
            Map<Long, String> authorMap = new HashMap<>();
            //4.2根据用户id集合，获取所有参与回复的用户,authorMap.get(reply.authorId)
            //每个用户都会关联一条或多条评论
            if (!authorIds.isEmpty()) {
                LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.in(User::getId, authorIds);
                List<User> authors = userService.list(userWrapper);
                authorMap = authors.stream()
                        .collect(Collectors.toMap(User::getId, User::getUsername));
            }
            
            // 封装到VO对象
            ForumPostDetailVO forumPostDetailVO = new ForumPostDetailVO();
            forumPostDetailVO.setId(post.getId());
            forumPostDetailVO.setAuthorId(post.getAuthorId());
            forumPostDetailVO.setCategoryId(post.getCategoryId());
            forumPostDetailVO.setCategoryName(category.getName());
            forumPostDetailVO.setTitle(post.getTitle());
            forumPostDetailVO.setContent(post.getContent());
            forumPostDetailVO.setPostAuthor(userService.getById(post.getAuthorId()).getUsername());
            forumPostDetailVO.setViewCount(post.getViewCount());
            forumPostDetailVO.setReplyCount(post.getReplyCount());
            forumPostDetailVO.setLastReplyTime(post.getLastReplyTime());
            forumPostDetailVO.setIsTop(post.getIsTop());
            forumPostDetailVO.setIsElite(post.getIsElite());
            forumPostDetailVO.setStatus(post.getStatus());
            forumPostDetailVO.setCreatedTime(post.getCreatedTime());
            forumPostDetailVO.setUpdatedTime(post.getUpdatedTime());
            forumPostDetailVO.setReplyPage(resultPage);
            forumPostDetailVO.setAuthorMap(authorMap);
            
            return forumPostDetailVO;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    // 回复帖子
    public Map<String, Object> replyPost(ForumReply reply, Long postId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("redirect", "redirect:/login");
                return result;
            }
            ForumPost post = this.getById(postId);
            post.setReplyCount(post.getReplyCount() + 1);
            this.updateById(post);
            reply.setAuthorId(user.getId());
            reply.setPostId(postId);
            forumReplyService.save(reply);
            result.put("success", true);
            result.put("redirect", "redirect:/forum/post/" + postId);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "回复帖子失败: " + e.getMessage());
        }
        return result;
    }
}